package com.ybwh.springboot2.common.mybatis.plugin.result.nullcovert;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
@Slf4j
public class ToNullValInterceptor implements Interceptor {



    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        log.debug("进入数据脱敏拦截器...");
        if (result instanceof List) {
            List<?> resultList = (List<?>) result;
            for (Object obj : resultList) {
                doSensitiveFields(obj);
            }
        } else if (result instanceof Map) {
            Map<?, ?> resultMap = (Map<?, ?>) result;
            for (Object obj : resultMap.values()) {
                doSensitiveFields(obj);
            }
        } else {
            doSensitiveFields(result);
        }
        return result;
    }

    private void doSensitiveFields(Object obj) throws IllegalAccessException, InstantiationException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(ToNullVal.class)) {
                continue;
            }

            field.setAccessible(true);
            Object fval = field.get(obj);
            if (fval == null) {
                return;
            }

            if(shouldSetNull(field,fval)){
                field.set(obj, null);
            }

        }
    }

    private boolean shouldSetNull(Field field, Object fval) throws InstantiationException, IllegalAccessException {
        ToNullVal toNullVal = field.getAnnotation(ToNullVal.class);
        String tval = toNullVal.targetVal();
        //  处理特殊类型
        if(!Objects.equals(NoOp.class,toNullVal.toStringWay())){
            if(Objects.equals(tval,toNullVal.toStringWay().newInstance().convertToString(fval))){
                return true;
            }
        }else {
            // TODO 常规的 BigDecimal/LocalDateTime之类的要内置处理

            if(Objects.equals(tval,fval.toString())){
                return true;
            }
        }




        return false;


    }
}